class Kitchen extends egret.Sprite {
  private static UUID = 0;
  private _foods = new Map<Food, number>();
  private _workbench = new Map<number, Workbench>();
  private _workbenchCount = 2;
  private _observer = Observer.getInstance();
  private _workManager!: EGame.WorkManager;

  constructor() {
    super();
    this.width = 1000;
    this.height = 1000;
    this.y = 300;
  }

  init() {
    this.initWorkbench();
    this.initWorkManager();
  }

  initWorkManager() {
    this._workManager = new EGame.WorkManager(this._workbenchCount);
  }

  initWorkbench() {
    for (let i = 0; i < this._workbenchCount; i++) {
      const bench = new Workbench(this);
      bench.x = 120 * i;
      this.addChild(bench);
      this._workbench.set(i, bench);
    }
  }

  async receive(food: Food) {
    const job = { id: Kitchen.UUID++, work: async () => {
      const bench = this._workbench.get(job.id % this._workbenchCount) as Workbench;
      await bench.work(food);
    }};
    await new Promise((resolve) => {
      this._workManager.receive(job);
      const callback = (e: { job: EGame.IJob; result: any; }): void => {
        if (job.id === e.job.id) {
          resolve(undefined);
          this._workManager.removeWorkedListener(callback);
        }
      };
      this._workManager.addWorkedListener(callback)
    });
  }
}
class Workbench extends egret.Sprite {
  private _processBar = new ProcessBar();
  constructor(private _kitchen: Kitchen) {
    super();
    this.graphics.beginFill(0x0000ff);
    this.graphics.drawRect(0, 0 , 100, 100);
  }
  async work(food: Food) {
    const clone = food.clone();
    this.addChild(clone);
    await this._process(food.markTime);
    this.removeChild(clone);
  }

  private _process(duration: number) {
    return new Promise((resolve) => {
      this._processBar.y = -20;
      this.addChild(this._processBar)
      egret.Tween.removeTweens(this._processBar);
      this._processBar.process = 0;
      egret.Tween.get(this._processBar).to({process: 1}, duration).call(() => {
        resolve(undefined);
        this.removeChild(this._processBar);
        egret.Tween.removeTweens(this._processBar);
      }, this)
    })
  }


}

interface IFoodConfig {
  id: number;
  resKey: string;
  price: number;
  name: string;
  markTime: number;
}

class Food extends egret.Bitmap {
  private _price = 1;
  private _id: number;
  private _markTime: number;
  constructor(private _config: IFoodConfig) {
    super();
    this._id = _config.id;
    this.name = _config.name;
    this.price = _config.price;
    const res = RES.getRes(_config.resKey);
    this.texture = res;
    this._markTime = _config.markTime;
  }

  set price(v: number) {
    if (v < 1) {
      return;
    }
    this._price = v;
  }

  get markTime() {
    return this._markTime;
  }

  get price() {
    return this._price;
  }

  clone() {
    return new Food(this._config);
  }
}
